//
//  HomeBannerADViewController.swift
//  MOMAEducation
//
//  Created by Rdxer on 2017/11/17.
//  Copyright © 2017年 Rdxer. All rights reserved.
//

import UIKit
import MBProgressHUD
import WebKit

open class SimpleWebViewController: UIViewController {

    var url:URL?
    var hidesBarsOnSwipe = false
    var request:URLRequest?
    var webView  = UIWebView.init()
//    var progressView = UIProgressView()
    var nController:UINavigationController?
    
    var needShowHud = true
    
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        webView.scalesPageToFit = true
        
        view.addSubview(webView)

        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        webView.loadRequest(request ?? URLRequest.init(url: url!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 20))
        
        webView.delegate = self
        
        let image =  #imageLiteral(resourceName: "nav_bar_back_icon")
        let barButton = UIBarButtonItem.init(image: image, style: .done, target: self, action: #selector(backItemPressed))
        
        self.navigationItem.leftBarButtonItem = barButton
    
    }
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if hidesBarsOnSwipe {
            navigationController?.hidesBarsOnSwipe = true
            nController = navigationController
        }
    }
    
    open override func viewDidDisappear(_ animated: Bool) {
        if hidesBarsOnSwipe {
            nController?.hidesBarsOnSwipe = false
        }
        super.viewDidDisappear(animated)
    }

    @objc func backItemPressed() {
        if webView.canGoBack {
            webView.goBack()
        }else{
            if let nav = self.navigationController {
                nav.popViewController(animated: true)
            }
        }
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle{
        get{
            return .lightContent
        }
    }
    var hud : MBProgressHUD?
}
extension SimpleWebViewController:UIWebViewDelegate{
    
    open func webViewDidStartLoad(_ webView: UIWebView) {
        if needShowHud {
            hud = addTransparentHUDTo(view)
        }
    }
    
    open func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        if needShowHud {
            hud?.hide(animated: true)
        }
    }
    open func webViewDidFinishLoad(_ webView: UIWebView) {
        if needShowHud {
            hud?.hide(animated: true)
        }
        if title == nil {
            title = webView.stringByEvaluatingJavaScript(from: "document.title")
        }
    }
    
}

